package com.zs.propertymanage.service.impl.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zs.propertymanage.dataObj.DTO;
import com.zs.propertymanage.dataObj.GeneralExtra;
import com.zs.propertymanage.dataObj.R;
import com.zs.propertymanage.dataObj.entity.WorkOrder;
import com.zs.propertymanage.dataObj.workorderExtra.WorkOrderCategory;
import com.zs.propertymanage.dataObj.workorderExtra.WorkOrderCategoryFlow;
import com.zs.propertymanage.dataObj.workorderExtra.WorkOrderProcess;
import com.zs.propertymanage.mapper.WorkOrderMapper;
import com.zs.propertymanage.service.impl.WorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WorkOrderServiceImpl implements WorkOrderService {

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Override
    public R getAllWorkOrder(String search, Integer currentPage, Integer pageSize) {
        Integer start = (currentPage - 1) * pageSize;
        List<WorkOrder> list = workOrderMapper.getAllWorkOrder(search, start, pageSize);
        Integer total = workOrderMapper.getAllWorkOrderCount(search);
        DTO<WorkOrder> workOrderDto = new DTO(list, total);
        return total == 0 ? R.error("未查询到工单列表") : R.ok("查询工单列表成功", workOrderDto);
    }

    @Override
    public R getAllCategory() {
        List<WorkOrderCategory> list = workOrderMapper.getAllCategory();
        return list.size() == 0 ? R.error("未查询到工单分类列表") : R.ok("查询工单分类列表成功", list);
    }

    @Override
    public R addCategory(String categoryName) {
        if (categoryName == null || categoryName.equals("")) {
            return R.error("工单分类名称不能为空");
        }
        Integer result = workOrderMapper.addCategory(categoryName);
        return result == 0 ? R.error("添加工单分类失败") : R.ok("添加工单分类成功");
    }

    @Override
    public R deleteCategory(Integer id) {
        // 首先删除该分类下关联的职责人员
        int result1 = workOrderMapper.deleteCategoryDuty(id);
        if (result1 == 0)
            return R.error("删除该分类下关联的职责人员失败");
        Integer result2 = workOrderMapper.deleteCategory(id);
        return result2 == 0 ? R.error("删除工单分类失败") : R.ok("删除工单分类成功");
    }

    @Override
    public R getAllWorkOrderStatus() {
        List<GeneralExtra> list = workOrderMapper.getAllWorkOrderStatus();
        return list.size() == 0 ? R.error("未查询到工单状态列表") : R.ok("查询工单状态列表成功", list);
    }

    @Override
    public R addWorkOrderStatus(String statusName) {
        if (statusName == null || statusName.equals("")) {
            return R.error("工单状态名称不能为空");
        }
        Integer result = workOrderMapper.addWorkOrderStatus(statusName);
        return result == 0 ? R.error("添加工单状态失败") : R.ok("添加工单状态成功");
    }

    @Override
    public R deleteWorkOrderStatus(Integer id) {
        Integer result = workOrderMapper.deleteWorkOrderStatus(id);
        return result == 0 ? R.error("删除工单状态失败") : R.ok("删除工单状态成功");
    }

    @Override
    public R setCategoryFlow(WorkOrderCategoryFlow flow) {
        Integer categoryId = flow.getCategoryId();
        Integer[] flowIds = flow.getFlow();
        StringBuilder flowStr = new StringBuilder();
        for (Integer flowId : flowIds) {
            flowStr.append(flowId).append(",");
        }
        Integer result = workOrderMapper.setCategoryFlow(categoryId, flowStr.toString());
        return result == 0 ? R.error("设置工单分类流程失败") : R.ok("设置工单分类流程成功");
    }

    @Override
    public R getWorkOrderById(String workOrderId) {
        WorkOrder workOrder = workOrderMapper.getWorkOrderById(workOrderId);
        return workOrder == null ? R.error("未查询到工单信息") : R.ok("查询工单信息成功", workOrder);
    }

    @Override
    public R getHandleInfo(String workOrderId) {
        WorkOrder workOrder = workOrderMapper.getWorkOrderById(workOrderId);    // 获取当前处理的工单对象
        // 获取工单流程信息，并将其转换为对象数组
        String processStr = workOrder.getProcess();
        String[] processArr;
        processArr = processStr.split("&process-split&");

        List<WorkOrderProcess> processList = new ArrayList<>();
        for (String s : processArr) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                WorkOrderProcess process = objectMapper.readValue(s, WorkOrderProcess.class);
                processList.add(process);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return R.ok("查询工单处理信息成功", processList);
    }

    @Override
    public R switchCloseStatus(String workOrderId) {
        WorkOrder workOrder = workOrderMapper.getWorkOrderById(workOrderId);
        Integer closeStatus = workOrder.getCloseStatus().equals(WorkOrder.CLOSE_STATUS_OPEN) ? WorkOrder.CLOSE_STATUS_CLOSE : WorkOrder.CLOSE_STATUS_OPEN;
        workOrder.setCloseStatus(closeStatus);
        return workOrderMapper.changeCloseStatus(workOrderId, closeStatus) > 0 ? R.ok("切换工单开关状态成功") : R.error("切换工单开关状态失败");
    }

    @Override
    public R setCategoryDuty(Integer categoryId, String[] duty) {
        // 删除旧职责人员
        int result1 = workOrderMapper.deleteCategoryDuty(categoryId);
        if (result1 == 0) {
            return R.error("清除工单分类旧职责人员失败");
        }
        // 新职责人员为空则直接返回更新成功
        if (duty == null || duty.length == 0)
            return R.ok("设置工单分类职责人员成功");
        // 新职责人员不为空，批量插入数据库中
        List<Map<String, String>> dutyList = new ArrayList<>();
        for (String dutyId : duty) {
            Map<String, String> dutyMap = new HashMap<>();
            dutyMap.put("id", UUID.randomUUID().toString());
            dutyMap.put("wcid", categoryId.toString());
            dutyMap.put("eid", dutyId);
            dutyList.add(dutyMap);
        }
        int result2 = workOrderMapper.setCategoryDuty(categoryId, dutyList);
        return result2 > 0 ? R.ok("设置工单分类职责人员成功") : R.error("设置工单分类职责人员失败");

//        int result = workOrderMapper.setCategoryDuty(categoryId, "," + duty + ",");     // 前后用逗号包起来是为了方便按职责查询工单（where duty like '%,id,%'）
//        return result > 0 ? R.ok("设置工单分类职责人员成功") : R.error("设置工单分类职责人员失败");
    }

    @Override
    public R getCategoryDuty(Integer categoryId) {
        List<Map<String, String>> dutyList = workOrderMapper.getCategoryDuty(categoryId);
        return dutyList == null ? R.error("未查询到工单分类职责人员") : R.ok("获取工单分类职责人员成功", dutyList);
    }
}
